package com.sunny.ninepictureview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;


/**
 * 添加图片的九图控件
 */
public class NineAddPictureView extends ViewGroup {

    public interface genImageViewListener {
        /**
         * 添加要显示的图片
         *
         * @param path path为 ADD_BUTTON_PATH 时为创建添加按钮
         * @return
         */
        ImageView getImageView(String path);
    }

    //生成图片的接口
    private genImageViewListener genImageViewListener;
    //九张图片的path
    private List<String> paths;
    private OnItemClickListener onItemClickListener;
    /**
     * 添加按钮的path
     */
    public static final String ADD_BUTTON_PATH = "ADD.BUTTON.PATH";


    /**
     * 默认图片间隔
     */
    private final int ITEM_GAP = 3;
    private final int DEFAULT_WIDTH = 140;
    /**
     * 图片之间的间隔
     */
    private int gap;
    private int columns;
    private int rows;
    private int totalWidth;
    private Context context;
    private int singleWidth = 0;
    private int singleHeight = 0;
    private int defaultWidth;
    private int defaultHeight;


    public NineAddPictureView(Context context) {
        this(context, null);
    }

    public NineAddPictureView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NineAddPictureView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        gap = dip2px(context, ITEM_GAP);
        defaultWidth = defaultHeight = dip2px(context, DEFAULT_WIDTH);
    }

    public NineAddPictureView.genImageViewListener getGenImageViewListener() {
        return genImageViewListener;
    }

    public void setGenImageViewListener(NineAddPictureView.genImageViewListener genImageViewListener) {
        this.genImageViewListener = genImageViewListener;
    }

    public void setDefaultWidth(int defaultWidth) {
        this.defaultWidth = defaultWidth;
    }

    public void setDefaultHeight(int defaultHeight) {
        this.defaultHeight = defaultHeight;
    }


    /**
     * 初始化状态，添加按钮初始化
     */
    public void initState() {
        paths = new ArrayList<>();
        addPicture(ADD_BUTTON_PATH);
    }

    public void addPicture(String path) {
        //初始化，第一个显示添加按钮
        if (ADD_BUTTON_PATH.equals(path)) {
            paths.add(path);
            generateChildrenLayout(paths.size());
            addView(genImageViewListener.getImageView(ADD_BUTTON_PATH), generateDefaultLayoutParams());
            requestLayout();
        } else if (paths.size() == 9 && ADD_BUTTON_PATH.equals(paths.get(8))) { //第九张图片是添加按钮
            paths.set(8, path);
            removeViewAt(8);
            addView(genImageViewListener.getImageView(path), generateDefaultLayoutParams());
            requestLayout();
            //最后一个不是添加按钮，添加一张图片，添加按钮向后移动一位
        } else if (paths.size() < 9) {  //不满9张图，可以添加
            //初始化布局形状
            paths.add(paths.size() - 1, path);
            //因为paths已经添加元素了。所以要减2
            addView(genImageViewListener.getImageView(path), paths.size() - 2, generateDefaultLayoutParams());
            generateChildrenLayout(paths.size());
            requestLayout();
        }

    }


    /**
     * 移除指定位置图片
     *
     * @param position
     */
    public void removePicture(int position) {
        if (position >= 0 && position < paths.size()) {
            //不可以删除添加按钮
            if (ADD_BUTTON_PATH.equals(paths.get(position))) {
                return;
            }
            //9张图片，应该把删除按钮添加上
            if (paths.size() == 9 && !ADD_BUTTON_PATH.equals(paths.get(8))) {
                //初始化布局形状
                paths.remove(position);
                paths.add(ADD_BUTTON_PATH);
                removeViewAt(position);
                addView(genImageViewListener.getImageView(ADD_BUTTON_PATH), generateDefaultLayoutParams());
                requestLayout();
            } else {
                paths.remove(position);
                removeViewAt(position);
                generateChildrenLayout(paths.size());
                requestLayout();
            }
        }
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        totalWidth = sizeWidth - getPaddingLeft() - getPaddingRight();
        if (paths.size() > 0) {
            int measureWidth, measureHeight;
            int childrenCount = paths.size();
            singleWidth = (totalWidth - gap * (columns - 1)) / columns;
            singleHeight = singleWidth;
            measureChildren(MeasureSpec.makeMeasureSpec(singleWidth, MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(singleHeight, MeasureSpec.EXACTLY));
            measureWidth = singleWidth * columns + gap * (columns - 1);
            measureHeight = singleHeight * rows + gap * (rows - 1);
            setMeasuredDimension(sizeWidth, measureHeight);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        layoutChildrenView();
    }

    private void layoutChildrenView() {
        if (paths.size() == 0) {
            return;
        }
        int childrenCount = paths.size();
        for (int i = 0; i < childrenCount; i++) {
            int[] position = findPosition(i);
            int left = (singleWidth + gap) * position[1] + getPaddingLeft();
            int top = (singleHeight + gap) * position[0] + getPaddingTop();
            int right = left + singleWidth;
            int bottom = top + singleHeight;
            ImageView childrenView = (ImageView) getChildAt(i);
            childrenView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            final int itemPosition = i;
            childrenView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClickListener != null) {
                        if (ADD_BUTTON_PATH.equals(paths.get(itemPosition))) {
                            onItemClickListener.onAddButtonClick();
                        } else {
                            onItemClickListener.onItemClick(v, itemPosition);
                        }
                    }
                }
            });
            childrenView.layout(left, top, right, bottom);
        }
    }


    private int[] findPosition(int childNum) {
        int[] position = new int[2];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                if ((i * columns + j) == childNum) {
                    position[0] = i;//行
                    position[1] = j;//列
                    break;
                }
            }
        }
        return position;
    }

    public int getGap() {
        return gap;
    }

    public void setGap(int gap) {
        this.gap = gap;
    }

    /**
     * 根据图片个数确定行列数量
     * 对应关系如下
     * num   row  column
     * 1     1     5
     * 2     1     5
     * 3     1    5
     * 4     1    5
     * 5    1    5
     * 6    2    5
     * 7    2    5
     * 8    2   5
     * 9    2    5
     *
     * @param length
     */
    private void generateChildrenLayout(int length) {
        if (length <= 5) {
            rows = 1;
        } else {
            rows = 2;
        }
        columns = 5;
    }

    /**
     * dp to px
     */
    private int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);

        void onAddButtonClick();
    }
}
